import { MongoClient } from "mongodb";

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    const db = client.db("hello");
    const res = await db.command({ ping: 1 }); // 测试数据库是否成功
    console.log("connected", res);
    const userCollection = db.collection("user");
    const teamCollection = db.collection("team");
    const pipeLine = [
      { $match: { age: { $gt: 30 } } }, // 过滤
      { $group: { _id: "$team", total: { $sum: "$age" }, count: { $sum: 1 }, avg: { $avg: "$age" } } }, // 分组
      { $sort: { total: 1 } }, // 排序
    ];
    const results = await userCollection.aggregate(pipeLine).toArray();
    console.log(results);
  } catch (error) {
    console.error("error", error);
  } finally {
    await client.close();
  }
}

run();
